<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="google" value="notranslate">
  <link rel="shortcut icon" href="static/favicon.ico">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <title><%= htmlWebpackPlugin.options.title %></title>
  <% if (htmlWebpackPlugin.options.sentryConfig) { %>
  <!-- Sentry error logging to help with finding bugs -->

  <script src="https://cdn.ravenjs.com/3.22.1/raven.min.js" crossorigin="anonymous"></script>
  <script>
    Raven.config(<%= htmlWebpackPlugin.options.sentryConfig %>).install();
  </script>
  <!-- /Sentry -->
  <% } %>
  <script>
    var devHost = "";//http://localhost:9998
    var logourl = "";
    var theRequest = { id: 0, p: 0 };
    function getCookie(params) {
      var cookieList = document.cookie.split(";");
      for (var i = 0; i < cookieList.length; i++) {
        var cookieItem = cookieList[i].split("=")
        if (cookieItem[0].trim() == params) {
          return cookieItem[1]
        }
      }
      return ""
    }
    function dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], "a.sb3", {
        type: mime
      })
    }
    var curretWork = {};

    window.scratchConfig = {
      logo: {
        show: true
        , url: logourl
        , handleClickLogo: () => {
          window.location.href = "/";
        }
      },
      menuBar: {
        color: '#34676c'
      },
      shareButton: {
        show: true,
        buttonName: "保存",
        handleClick: () => {
          //点击分享按钮 
          window.scratch.getProjectCover(cover => {
            //TODO 获取到作品截图

          })
          window.scratch.getProjectFile(file => {
            var token = sessionStorage.getItem("token")
            if (!token || token.length < 10) {

              alert("需要先登录 才能保存");
              window.location.href = "/";
              return

            }
            //TODO 获取到项目文件
            let formData = new FormData()
            formData.append("file", file);
            formData.append("workname", window.scratch.getProjectName());
            formData.append("ext", ".sb3");
            axios.put(devHost + '/api/class/updateStudentWork/' + theRequest.id, formData, {
              headers: {
                'token': token,
                "Content-Type": "multipart/form-data;"
              }

            })
              .then(function (response) {

                if (theRequest.id == 0) {
                  alert("保存成功，正重新载入");
                  window.location.href = "/studentwork/scratch3/index.html?p=0&id=" + response.data.data.Id;
                }else{
                
                  alert("保存成功");
                }
                // console.log(res);

              })
              .catch(function (error) {
                console.log(error);
              });
          })
          // 获取到项目名
          // var projectName = window.scratch.getProjectName()
          // console.log("========---------========", projectName);
        }
      },
      profileButton: {
        show: true,
        buttonName: sessionStorage.getItem("token") ? "已经登录" : "尚未登录",
        handleClick: () => {
          //  window.location.href = "/";
          //点击profile按钮

        }
      },
      handleVmInitialized: (vm) => {
        window.vm = vm


        let url = location.search;
        if (url.indexOf('?') != -1) {
          var str = url.substr(1)
          var strs = str.split('&')
          for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
          }
        }
        axios.get(devHost + '/api/platform/getWebSiteInfo/0')
          .then(function (response) {
            var res = response.data.data;
            window.scratchConfig.logo.url = res.logo;//"http://www.sendrobot.cn/img/header/Logo-line.png";
            document.title = res.Label + '学员作品';
            if (res.shortcut) {
              document.getElementById("shortcut").href = res.shortcut;
            }
          })
          .catch(function (error) {
            console.log(error);
          });

        console.log("VM初始化完毕")

      },
      handleProjectLoaded: () => {
       
        console.log("作品载入完2毕", theRequest)

      },
      handleDefaultProjectLoaded: () => {

        //默认作品加载完毕，一般在这里控制项目加载
        axios.get(devHost + '/api/class/getOneStudentWorks/' + theRequest.id)
          .then(function (response) {
            if (!response.data.data) {
              return
            }

            var workurl;
            if (response.data.data && response.data.data.Work) {
              workurl = response.data.data.Work;
            }
             
            window.scratch.loadProject("/" +workurl+ "?nowtime=" + new Date().getTime(), () => {
              window.scratch.setProjectName(response.data.data.WorkName) 
              document.title = response.data.data.WorkName;
            })

          })
          .catch(function (error) {
            console.log(error);
          });


      },
      //若使用官方素材库请删除本配置项
      assetCDN: '/studentwork/scratch3/static' //http://scratch.qiniu.xxx.com'
    }


  </script>
</head>

<body>
  <div id="scratch">

  </div>
</body>
<script>

</script>

</html>